package com.weyoung.common.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import com.weyoung.common.model.dto.TXOssSetDTO;
import java.util.UUID;

/**
 * @author qinbo
 * @version 1.0
 * @description: TODO
 * @date 2025/4/20 22:39
 */
@Component
public class UpLoadFiles {
    public String uploadToOss(MultipartFile file, TXOssSetDTO dto, String name) throws Exception {
        // 获取文件名
        String fileName = file.getOriginalFilename();
        if (fileName == null || fileName.isEmpty()) {
            throw new IllegalArgumentException("文件名不能为空");
        }

        // 提取文件后缀
        String fileExtension = getFileExtension(fileName);
        if (fileExtension == null || fileExtension.isEmpty()) {
            throw new IllegalArgumentException("文件后缀不能为空");
        }

        // 生成 UUID
        String uuid = UUID.randomUUID().toString();

        // 构建新的文件名
        String objectName = "file/" + uuid + "." + fileExtension;

        // 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(dto.getEndpoint(), dto.getSecretId(), dto.getSecretKey());
        try {
            // 上传文件到 OSS
            ossClient.putObject(dto.getBucketName(), objectName, file.getInputStream());

            return dto.getPrefix() + "/" + objectName;
        } catch (OSSException oe) {
            throw new RuntimeException("OSS异常: " + oe.getErrorMessage(), oe);
        } catch (ClientException ce) {
            throw new RuntimeException("客户端异常: " + ce.getMessage(), ce);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    private String getFileExtension(String fileName) {
        if (fileName.lastIndexOf(".") != -1 && fileName.lastIndexOf(".") != 0) {
            return fileName.substring(fileName.lastIndexOf(".") + 1);
        } else {
            return null;
        }
    }
}
